package com.home.work.utils;

import com.home.work.constant.Resources;

import java.io.*;
import java.net.URL;

public class YmlUtils {
    /**
     * 将yml 文件内容以k-V形式存储到Resources.param中
     */
    public void getValue(){
        ClassLoader classLoader = getClass().getClassLoader();
        URL url = classLoader.getResource("application.yml");
        File file = new File(url.getFile());

        FileReader fileReader = null;
        BufferedReader bufferedReader = null;

        String previousLine = "";
        String currentLine = "";
        try {
            fileReader = new FileReader(file);
            bufferedReader = new BufferedReader(fileReader);
            while(currentLine != null ){
                currentLine = bufferedReader.readLine();
//                if(line.contains("port")){
//                    String[] split = line.split(": ");
//                    System.out.println(split[1]);
//                }
                if(currentLine != null){
                    if(currentLine.contains(":")){
                        if(currentLine.startsWith(" ")){
                            // 如果以空格开头，证明他是子元素
                            String[] split = currentLine.split(": ");
                            String key = previousLine+"."+(split[0]).trim();
                            String value = split[1].trim();
                            Resources.param.put(key,value);
                            previousLine = key;
                        }else{
                            // 证明他是父级元素
                            int i = currentLine.lastIndexOf(":");
                            previousLine = currentLine.substring(0,i);
                        }
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
